<template>
  <div class="settings-container">
    <div class="app-container">
      <el-card>
        <!-- 具体页面结构 -->
        <el-tabs>
          <!-- 放置页签 -->
          <el-tab-pane label="角色管理">
            <el-row style="height:60px">
              <el-button icon="el-icon-plus" size="small" type="primary" @click.native="showDialog = true,isEdit = false">新增角色</el-button>

            </el-row>
            <el-table :data="list">
              <el-table-column label="序号" width="120" type="index" />
              <el-table-column label="角色名称" width="240" prop="name" />
              <el-table-column label="描述" prop="description" />
              <el-table-column label="操作" align="center">
                <template v-slot="{row}">
                  <el-button size="small" type="success" @click="hAssignPer(row.id)">分配权限</el-button>
                  <el-button size="small" type="primary" @click.native="hEdit(row)">编辑</el-button>
                  <el-button size="small" type="danger" @click.native="hDel(row.id)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-row type="flex" justify="center" align="middle" style="height: 60px">
              <!-- 分页组件 -->
              <el-pagination
                :current-page="pageParams.page"
                :page-sizes="[2,3,5,8,10]"
                :total="total"
                :page-size="pageParams.pagesize"
                layout=" sizes, prev, pager, next, jumper"

                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </el-row>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog :title=" isEdit?'修改角色' :'添加角色'" :visible.sync="showDialog" @close="DClose">
        <el-form ref="roleForm" :model="roleForm" :rules="rules" label-width="100px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="roleForm.name" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="roleForm.description" />
          </el-form-item>
        </el-form>
        <!-- 底部 -->
        <el-row slot="footer" type="flex" justify="center">
          <el-col :span="6">
            <el-button size="small" @click="DClose">取消</el-button>
            <el-button size="small" type="primary" @click="hSubmit">确定</el-button>
          </el-col>
        </el-row>
      </el-dialog>
      <el-dialog title="分配权限" :visible.sync="perShowDialog">
        <assignPer :id="roleId" @success="hSuccess" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import assignPer from './assignPermission.vue'
import { getRole, addRoles, editRoles, delRoles } from '@/api/settings'
export default {
  components: {
    assignPer
  },
  data() {
    return {
      roleId: '', // 保存角色id
      perShowDialog: false,
      isEdit: false,
      showDialog: false,
      list: [],
      roleForm: {
        name: '',
        description: ''

      },
      rules: {
        name: [
          { required: true, message: '请输入角色的名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色的描述信息', trigger: 'blur' }
        ]
      },
      pageParams: {
        page: 1, // 页码值
        pagesize: 2 // 每页显示的条数
      },

      total: 0
    }
  },
  created() {
    this.loadRoles()
  },
  methods: {
    hSuccess() {
      // 子传父关闭窗口
      this.perShowDialog = false
    },
    hAssignPer(id) {
      this.perShowDialog = true
      this.roleId = id
    },
    DClose() {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: ''

      }
      this.showDialog = false
    },
    hDel(id) {
      this.$confirm('您确认要删除这个角色吗').then(
        async() => {
          const res = await delRoles(id)
          console.log(res)
          if (this.list.length === 1) {
            this.pageParams.page--
            if (this.pageParams.page <= 0) {
              this.pageParams.page = 1
            }
          }
          if (res.code === 10000) {
            this.loadRoles()
          }
        }
      ).catch(err => console.log(err))
    },
    async editClick() {
      try {
        const res = await editRoles(this.roleForm)
        console.log(res)
        // 重新渲染数据
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    hEdit(row) {
      this.isEdit = true
      console.log(row)
      // 因为row里的数据要是直接赋值给roleform会出现地址相同的情况，导致表单也跟着表格改变，所以我们可以使用浅拷贝让地址不相同
      this.roleForm = { ...row }
      this.showDialog = true
    },
    hSubmit() {
      // 确认提交
      this.$refs.roleForm.validate((valid) => {
        if (!valid) return new Error('校验未通过')
        // 校验通过
        // 发送添加请求

        this.isEdit ? this.editClick() : this.addClick()
      })
    },
    async addClick() {
      try {
        const { data } = await addRoles(this.roleForm)
        console.log(data)
        // 因为这里只是把新增的角色添加给后台了，页面并没有刷新，data里面的数据也还没有获取所以总数会少计算一条
        this.total++
        // 计算出最大的页码值, Math.ceil(总页数 / 页码值)
        const maxPage = Math.ceil(this.total / this.pageParams.pagesize)
        console.log(maxPage)
        this.pageParams.page = maxPage
        // 重新渲染数据
        this.loadRoles()
        this.showDialog = false
      } catch (error) {
        console.log(error)
      }
    },
    async loadRoles() {
      const res = await getRole(this.pageParams)

      this.list = res.data.rows
      this.total = res.data.total
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.pagesize = val
      this.loadRoles()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadRoles()
    }
  }
}
</script>
